package com.pricl.frame.common.utils;

import java.lang.reflect.Constructor;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.Collection;
import java.util.Map;

public class StringUtils {

	@SuppressWarnings("unchecked")
	public static <T> T valueOf(String value, Class<?> clazz) {
		if (value == null || clazz == null) {
			return null;
		}
		if (String.class.equals(clazz)) {
			return (T) value;
		}
		value = value.trim();
		if (value.length() == 0) {
			return null;
		}
		if (Boolean.class.equals(clazz) || Boolean.class.equals(clazz)) {
			return (T) Boolean.valueOf(value);
		}
		if (Byte.class.equals(clazz) || byte.class.equals(clazz)) {
			value = value.replaceAll(",", "");
			return (T) Byte.valueOf(value);
		}
		if (Character.class.equals(clazz) || char.class.equals(clazz)) {
			return (T) new Character(value.length() > 0 ? value.charAt(0) : '\0');
		}
		if (Short.class.equals(clazz) || short.class.equals(clazz)) {
			value = value.replaceAll(",", "");
			return (T) Short.valueOf(value);
		}
		if (Integer.class.equals(clazz) || int.class.equals(clazz)) {
			value = value.replaceAll(",", "");
			return (T) Integer.valueOf(value);
		}
		if (Long.class.equals(clazz) || long.class.equals(clazz)) {
			value = value.replaceAll(",", "");
			return (T) Long.valueOf(value);
		}
		if (Float.class.equals(clazz) || float.class.equals(clazz)) {
			value = value.replaceAll(",", "");
			return (T) Float.valueOf(value);
		}
		if (Double.class.equals(clazz) || double.class.equals(clazz)) {
			value = value.replaceAll(",", "");
			return (T) Double.valueOf(value);
		}
		if (BigDecimal.class.equals(clazz)) {
			value = value.replaceAll(",", "");
			return (T) new BigDecimal(value);
		}
		if (Date.class.isAssignableFrom(clazz)) {
			return (T) DateUtils.parse(value);
		}
		if (clazz == byte[].class) {
			return (T) value.getBytes();
		}
		if (Collection.class.isAssignableFrom(clazz) || Map.class.isAssignableFrom(clazz) || clazz.isArray()) {
			return null;
		}
		try {
			Constructor<?> c = clazz.getConstructor(new Class[] { String.class });
			if (c != null) {
				return (T) c.newInstance(value);
			}
		} catch (Exception e) {
		}
		return null;
	}
}
